

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import TodoView from '../views/TodoView.vue'
import AboutView from '../views/AboutView.vue'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', component: LoginView }, // 登录页（无需权限）
    // 核心页面：标记为需要登录
    { path: '/', component: HomeView, meta: { requiresAuth: true } },
    { path: '/todo', component: TodoView, meta: { requiresAuth: true } },
    { path: '/about', component: AboutView, meta: { requiresAuth: true } },
  ]
})

// 🔥 全局路由守卫：拦截需登录的页面
router.beforeEach((to, from, next) => {
  const requiresAuth = to.meta.requiresAuth; // 判断是否需要登录
  // 从 sessionStorage 读取登录状态（每次刷新后被 main.js 清除）
  const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true'; 

  if (requiresAuth && !isLoggedIn) {
    next('/login'); // 未登录 → 强制跳转到登录页
  } else {
    next(); // 已登录 / 无需登录 → 放行
  }
});

export default router





